<?php
namespace Home\Controller;
use Think\Controller;
use Think\Exception;

class IndexController extends Controller {
    private $page_num  =   5;
    private $like_num  =   6;
    private $u_id   =   1;

    public function __construct(){
        parent::__construct();
        $login_url  =   U('Home/Login/index');
        if(cookie("user_id")<1){
            header("Location:{$login_url}");
        }else{
            $this->u_id     =   intval(cookie("user_id"));
            $count = M('Notify')->where(array('to_user_id'=>$this->u_id,'is_view'=>0))->count();
            $this->assign('count',$count);            
        }
        $set = M('Set')->where(array('id'=>1))->find();
        $this->page_num = $set['page_num'];
        $this->like_num =  $set['like_num'];
    }

    public function index(){
        //“最新”帖子的条数
        $count  =   M('message')->where(array('status'=>1))->count();
        $total  =   ceil($count/$this->page_num);
        //“热门”帖子的条数
        $count  =   M('message')->where(array('status'=>1,'like_num'=>array('EGT',$this->like_num)))->count();
        $hot_total  =   ceil($count/$this->page_num);
        $this->assign('totalpage',$total);
        $this->assign('hot_total',$hot_total);
        $this->display();
    }
    /**
     * ajax 获取首页数据
     */
    public function ajaxIndex(){
        $cur_page   =   !isset($_GET['pagenum']) ? 1 : intval($_GET['pagenum']);
        $type       =   !empty($_GET['type'])    ? (string)$_GET['type'] : 'new';
        $where      =  $type=='new' ? 'status=1 and like_num>=0' : "status=1 and like_num>=".$this->like_num;

        if($cur_page == 1){
            $limit = "0,".$this->page_num;
        }else{
            //$pagenum= ($cur_page-1)*$this->page_num;
            //$limit  = "{$pagenum},".$this->page_num;
            /*****   新规则，由于手机端切换按钮，屏幕显示的条数应该，显示 0,page_num*page_size   *****/
            $new    =   $cur_page * $this->page_num;
            $limit  = "0,{$new}";
        }

        $data   =   M('message')->where($where)->order('add_time desc')->limit($limit)->select();
        //查找当前登录用户 与message_id之间 是否有点赞的记录
        if(!empty($data)){
            foreach($data as &$row){
                $count              =   M('like')->where(array('message_id'=>$row['message_id'],'user_id'=>$this->u_id))->count();
                
                $row['like_flag']   =   $count>0 ? 1 : 0;
                $row['like_num']    =   M('like')->where(array('message_id'=>$row['message_id']))->count();
                $row['comment_num'] =   M('comment')->where(array('message_id'=>$row['message_id']))->count();
                $row['user_sex']    =   M('users')->getFieldByUserId($row['user_id'],'sex');
                $row['headimgurl']  =   M('users')->getFieldByUserId($row['user_id'],'headimgurl');
                $row['con_count'] = mb_strlen($row['content'],'utf-8');
                $row['con_len'] = msubstr($row['content'],0,99);
            }
        }
        $this->assign('datas',$data);
        $this->display();
    }
    /**
     * 帖子 点赞 接口
     */
    public function like(){
        $id     =   intval(I('post.id'));
        if($id<0)   echo json_encode(array('state'=>-1,'msg'=>'参数错误!'));
        //开启事务
        M('like')->startTrans();
        try{
            $data['message_id']     =   $id;
            $data['user_id']        =   $this->u_id;
            $data['add_time']        =   time();
            $like_id                =   M('like')->add($data);
            //更新message表的like_num字段
            M('message')->where(array('message_id'=>$id))->setInc('like_num');

            // 插入 notify通知记录
            $notify['n_type']       =   0;
            $notify['user_id']      =   $this->u_id;  //当前点赞的用户
            $notify['to_user_id']   =   M('message')->getFieldByMessageId($id,'user_id');  //当前帖子的主人
            $notify['comment_id']   =   0;  //点赞是没有comment_id的
            $notify['add_time']     =   time();
            $notify['msg_id']       =   $id;
            M('notify')->add($notify);
            M('like')->commit();
            echo json_encode(array('state'=>1,'msg'=>'操作成功!'));
        }catch (Exception $e){
            M('like')->rollback();
            echo json_encode(array('state'=>-1,'msg'=>'操作失败!'));
        }
    }
    /*
     * 取消点赞
     * */
    public function not_like(){
        if(IS_POST){
            $id     =   intval(I('post.id'));
            if($id<0)   echo json_encode(array('state'=>-1,'msg'=>'参数错误!'));
            //更新message表的like_num字段
            $res1 =  M('message')->where(array('message_id'=>$id))->setDec('like_num');
            $notify['user_id']      =   $this->u_id;  //当前点赞的用户
            $notify['to_user_id']   =   M('message')->getFieldByMessageId($id,'user_id');  //当前帖子的主人
            $notify['msg_id']        =   $id;
            $res2 = M('notify')->where($notify)->delete();
        
            $data['message_id']     =   $id;
            $data['user_id']        =   $this->u_id;
            $res3 =  M('like')->where($data)->delete();
            if($res1 && $res2 && $res3 ){
                echo json_encode(array('state'=>1,'msg'=>'操作成功!'));
            }else{
                echo json_encode(array('state'=>-1,'msg'=>'操作失败!'));
            }
        }
    }
    /**
     * 帖子详情页面
     */
    public function detail(){
        $id     =   intval(I('get.id'));

        if($id<1)   $this->redirect(U('Home/Index/index'));
        $data   =   M('message')->where(array('message_id'=>$id))->find();
        //查找当前登录用户 与message_id之间 是否有点赞的记录
        $count  =   M('like')->where(array('message_id'=>$id,'user_id'=>$this->u_id))->count();
        $data['like_flag']   =   $count>0 ? 1 : 0;
        $data['user_sex']    =   M('users')->getFieldByUserId($data['user_id'],'sex');
        $data['headimgurl']    =   M('users')->getFieldByUserId($data['user_id'],'headimgurl');
        $data['like_num'] = M('like')->where(array('message_id'=>$id))->count();
        $data['comment_num'] = M('Comment')->where(array('message_id'=>$id))->count();
        $this->assign('datas',$data);
        $this->display();
    }
    /**
     * ajax获取 详情页数据
     */
    public function ajaxComment(){
        $id     =   intval(I('get.id'));

        if(empty($id))  echo json_encode(array('state'=>-1,'msg'=>'参数错误！'));

        $sql    =   "SELECT
                        lyb_comment .*, lyb_users.nickname,lyb_users.headimgurl
                    FROM
                        lyb_comment AS lyb_comment
                    LEFT JOIN lyb_users AS lyb_users ON lyb_comment.user_id = lyb_users.user_id
                    WHERE
                        lyb_comment .message_id =$id
                    ORDER BY lyb_comment.add_time desc";

        $comments   =   M('comment')->query($sql);
        //查看当前 用户 对哪些评论 点赞过
        if(!empty($comments)){
            foreach($comments as &$row){
                $num                        =   M('comment_like')->where(array('comment_id'=>$row['comment_id']))->count();
                $flag                       =   M('comment_like')->where(array('comment_id'=>$row['comment_id'],"u_id"=>$this->u_id))->count();
                $row['self_click_flag']     =   $flag==0 ? 0 : 1;
                $row['like_comment_num']    =   $num==0 ? 0 : $num;
            }
        }

        $this->assign('comments',$comments);
        $this->display();
    }
    /**
     * 用户 发送评论
     */
    public function addComment(){
        $msg_id     =   intval(I('post.msg_id'));   //帖子的ID编号
        $contents   =   (string)trim(I('post.content'));    //评论的内容

        if(empty($msg_id) || empty($contents))  echo json_encode(array('state'=>-1,'msg'=>'参数错误,请重试!!!'));
        if(mb_strlen($contents,'utf-8'))  echo json_encode(array('state'=>-1,'msg'=>'评论不能超过200字!!!'));
        //comment表增加一条记录 && message表的comment_num加1
        M('comment')->startTrans();
        try{
            $data['message_id']     =   $msg_id;
            $data['user_id']        =   $this->u_id;
            $data['content']        =   $contents;
            $data['add_time']       =   time();
            $com_id                 =   M('comment')->add($data);
            M('message')->where(array('message_id'=>$msg_id))->setInc('comment_num');
            // 插入 notify通知记录
            $notify['n_type']       =   1;
            $notify['user_id']      =   $this->u_id;  //当前点赞的用户
            $notify['to_user_id']   =   M('message')->getFieldByMessageId($msg_id,'user_id');  //当前帖子的主人
            $notify['comment_id']   =   $com_id;  //点赞是没有comment_id的
            $notify['add_time']       =   time();
            $notify['msg_id']       =   $msg_id;
            M('notify')->add($notify);
            M('comment')->commit();
            echo json_encode(array('state'=>1,'msg'=>'评论成功!!!'));
        }catch (Exception $e){
            M('comment')->rollback();
            echo json_encode(array('state'=>-1,'msg'=>'评论失败!!!'));
        }
    }
    /**
     * 用户对评论 点赞
     */
    public function userLikeComment(){
        $com_id     =   intval(I('post.comment_id'));
        $msg_id     =   intval(I('post.message_id'));
        $u_id     =   intval(I('post.user_id'));
        if(empty($com_id) || empty($msg_id) || empty($u_id))  echo json_encode(array('state'=>-1,'msg'=>'缺少点赞参数！！！'));

        //comment_like表增加一条记录 && comment表的lime_comment_num
        M("comment_like")->startTrans();
        try{
            $datas['u_id']      =   $this->u_id;
            $datas['comment_id']=   $com_id;
            $datas['add_time']  =   time();
            M("comment_like")->add($datas);
            M('comment')->where(array('comment_id'=>$com_id))->setInc('like_comment_num');
            // 插入 notify通知记录
            $notify['n_type']       =   0;
            $notify['user_id']      =   $this->uid;  //当前点赞的用户
//            $notify['to_user_id']   =   M('message')->getFieldByMessageId($msg_id,'user_id');  //当前帖子的主人;
            $notify['to_user_id']   =   $u_id;  //当前帖子的主人
            $notify['comment_id']   =   $com_id;  //点赞是没有comment_id的
            $notify['add_time']  =   time();
            $notify['msg_id']  =   $msg_id;
            M('notify')->add($notify);
            M("comment_like")->commit();
            echo json_encode(array('state'=>1,'msg'=>'点赞成功！！！'));
        }catch (Exception $e){
            M("comment_like")->rollback();
            echo json_encode(array('state'=>-1,'msg'=>'点赞失败！！！'));
        }
    }
    /*
     * 对评论取消点赞
     * */
    public function NotuserLikeComment(){
        if(IS_POST){
            $com_id     =   intval(I('post.comment_id'));
            $msg_id     =   intval(I('post.message_id'));
            $u_id     =   intval(I('post.user_id'));
            if(empty($com_id) || empty($msg_id) || empty($u_id))  echo json_encode(array('state'=>-1,'msg'=>'缺少点赞参数！！！'));
           $res1 =  M('comment')->where(array('comment_id'=>$com_id))->setDec('like_comment_num');
            $datas['u_id']      =   $this->u_id;
            $datas['comment_id']=   $com_id;
            $res2 =   M("comment_like")->where($datas)->delete();
            $notify['user_id']      =   $this->uid;  //当前点赞的用户
            $notify['to_user_id']   =   $u_id;  //当前帖子的主人
            $notify['comment_id']   =   $com_id;  //点赞是没有comment_id的
            $notify['msg_id']  =   $msg_id;
            $res3 =   M('notify')->where($notify)->delete();
            if($res1 && $res2 && $res3){
                echo json_encode(array('state'=>1,'msg'=>'操作成功！！！'));
            }else{
                echo json_encode(array('state'=>-1,'msg'=>'操作失败！！！'));
            }
        }
    }
    /**
     * 用户举报帖子
     */
    public function jubao(){
        if(IS_POST){
            $msg_id     =   intval(I('post.msg_id'));
            $content    =   (string)I('post.content');
            $data['message_id'] =   $msg_id;
            $data['user_id']    =   $this->u_id;
            $data['content']    =   $content;
            $data['add_time']   =   time();
            $r_id   =   M('report')->add($data);
            if($r_id!==false)
                echo json_encode(array('state'=>1,'msg'=>'操作成功！！！'));
            else
                echo json_encode(array('state'=>-1,'msg'=>'操作失败！！！'));
        }else{
            $tie_id     =   intval(I('get.tie_id'));
            $this->assign('tie_id',$tie_id);
            $this->display();
        }
    }
    /**
     * 展示 帖子发布页面
     */
    public function publish(){
        if (IS_POST) {  //提交帖子信息
            $flag       =   intval(I('post.flag'));
            $contents   =   (string)I('post.contents');
            
            if($contents=="")   echo json_encode(array('state'=>-1,'msg'=>'帖子信息不能为空！！！'));
            if(mb_strlen($contents,'utf-8')>200)   echo json_encode(array('state'=>-1,'msg'=>'帖子信息不能为空！！！'));
            $data['content']    =   $contents;
            $data['user_id']    =   $this->u_id;
            $user_name          =   M('users')->getFieldByUserId($this->u_id,'nickname');
            $data['user_name']  =   $user_name=="" ? "暂无昵称" : $user_name;
            $data['is_show_name']    =   $flag;
            $data['add_time']   =   time();

            //插入 message表
            $msg_id             =   M('message')->add($data);

            if($msg_id!==false)
                echo json_encode(array('state'=>1,'msg'=>'操作成功！！！'));
            else
                echo json_encode(array('state'=>-1,'msg'=>'操作失败！！！'));
        }else{
            $this->display();
        }
    }
    /**
    ** 个人中心
    */
    public function ucenter(){
        $message_num=   M('Message')->where(array('status'=>1,'user_id'=>$this->u_id))->count();
        $join = 'left join '.C('DB_PREFIX').'message as m on l.message_id=m.message_id';
        $like_num  =   M('Like')->alias('l')->join($join)->where(array('l.user_id'=>$this->u_id,'m.status'=>1))->count();
        $row        =   M('users')->where(array('user_id'=>$this->u_id))->find();
        $this->assign('row',$row);
        $this->assign('message_num',$message_num);
        $this->assign('like_num',$like_num);
        $this->display();
    }

    /**
     * 个人中心消息列表
     */
    public function notify_list(){
        $user_id = $this->u_id;//暂时写死
        M('Notify')->where(array('to_user_id'=>$user_id))->setField('is_view',1);
        $count = M('Notify')->where(array('to_user_id'=>$user_id))->count();
        $total = ceil($count/$this->page_num);
        $this->assign('totalpage',$total);
        $this->display();
    }
    public function ajax_notify(){
        $user_id = $this->u_id;//暂时写死
        $cur_page   =   !isset($_GET['pagenum']) ? 1 : intval($_GET['pagenum']);
        if($cur_page == 1){
            $limit = "0,".$this->page_num;
        }else{
            $pagenum= ($cur_page-1)*$this->page_num;
            $limit  = "{$pagenum},".$this->page_num;
        }
        $join  = 'left join '.C('DB_PREFIX').'message as m on n.msg_id=m.message_id';
        $data   =   M('Notify')->alias('n')->field('n.*')->join($join)->where(array('n.to_user_id'=>$user_id,'m.status'=>1))->order('n.n_id desc')->limit($limit)->select();
//        echo M()->_sql();exit;
        foreach ($data as &$d){
            if($d['n_type'] == 0){
                if($d['comment_id'] >0 && $d['msg_id'] >0){
                    $d['n_type_msg'] = '有人赞了你的评论';
                }else{
                    $d['n_type_msg'] = '有人赞了你的帖子';
                }
            }else{
                $coment =  M('Comment')->field('add_time,content')->where(array('comment_id'=>$d['comment_id']))->find();
                $d['n_type_msg'] = '有人评论了你的帖子';
                $d['comment'] = msubstr($coment['content'],0,20);
            }
            $d['time'] = date('Y-m-d H:i:s',$d['add_time']);
            $content = M('Message')->where(array('message_id'=>$d['msg_id']))->getField('content');
            $d['content'] = msubstr($content,0,20);
        }
        $this->assign('datas',$data);
        $this->display();
    }
    /**
     * 个人中心反馈
     */
    public function tickling(){
        if(IS_POST){
            $user_id = $this->u_id;//暂时写死
            $data['user_id'] = $user_id;
            $data['content'] = I('post.contents');
            $data['is_show_name'] = I('post.flag');
            $data['add_time'] = time();
            if(trim($data['content']) == ''){
                $this->error('请输入反馈内容');
            }
            $res = M('Tickling')->add($data);
            if($res!==false)
                echo json_encode(array('state'=>1,'msg'=>'操作成功！！！'));
            else
                echo json_encode(array('state'=>-1,'msg'=>'操作失败！！！'));
        }else{
            $this->display();
        }

    }
    public function my_message(){
        $count  =   M('message')->where(array('status'=>1,'user_id'=>$this->u_id))->count();
        $total  =   ceil($count/$this->page_num);
        $this->assign('totalpage',$total);
        $this->display();
    }
    /*
     * ajax 获取帖子列表
     * */
    public function ajax_my_message(){
        $cur_page   =   !isset($_GET['pagenum']) ? 1 : intval($_GET['pagenum']);
        $where['status'] = 1;
        $where['user_id'] = $this->u_id;

        if($cur_page == 1){
            $limit = "0,".$this->page_num;
        }else{
            $pagenum= ($cur_page-1)*$this->page_num;
            $limit  = "{$pagenum},".$this->page_num;
        }

        $data   =   M('message')->where($where)->order('add_time desc')->limit($limit)->select();

        //查找当前登录用户 与message_id之间 是否有点赞的记录
        if(!empty($data)){
            foreach($data as &$row){
                 $count              =   M('like')->where(array('message_id'=>$row['message_id'],'user_id'=>$this->u_id))->count();
                
                $row['like_flag']   =   $count>0 ? 1 : 0;
                $row['like_num']    =   M('like')->where(array('message_id'=>$row['message_id']))->count();
                $row['comment_num'] =   M('comment')->where(array('message_id'=>$row['message_id']))->count();
                $row['user_sex']    =   M('users')->getFieldByUserId($row['user_id'],'sex');
                $row['headimgurl']  =   M('users')->getFieldByUserId($row['user_id'],'headimgurl');
                $row['con_count'] = mb_strlen($row['content'],'utf-8');
                $row['con_len'] = msubstr($row['content'],0,99);
            }
        }
        $this->assign('datas',$data);
        $this->display();
    }
    public function my_like(){
        $count  =   M('Like')->where(array('user_id'=>$this->u_id))->count();
        $total  =   ceil($count/$this->page_num);
        $this->assign('totalpage',$total);
        $this->display();
    }
    /*
    * ajax 获取喜欢帖子列表
    * */
    public function ajax_my_like(){
        $cur_page   =   !isset($_GET['pagenum']) ? 1 : intval($_GET['pagenum']);
        $where['m.status'] = 1;
        $where['l.user_id'] = $this->u_id;

        if($cur_page == 1){
            $limit = "0,".$this->page_num;
        }else{
            $pagenum= ($cur_page-1)*$this->page_num;
            $limit  = "{$pagenum},".$this->page_num;
        }
        $join = 'left join '.C('DB_PREFIX').'message as m on l.message_id=m.message_id';
        $data   =   M('Like')->alias('l')->join($join)->where($where)->order('l.add_time desc')->limit($limit)->select();
        //查找当前登录用户 与message_id之间 是否有点赞的记录
        if(!empty($data)){
            foreach($data as &$row){
                $count              =   M('like')->where(array('message_id'=>$row['message_id'],'user_id'=>$this->u_id))->count();
                
                $row['like_flag']   =   $count>0 ? 1 : 0;
                $row['like_num']    =   M('like')->where(array('message_id'=>$row['message_id']))->count();
                $row['comment_num'] =   M('comment')->where(array('message_id'=>$row['message_id']))->count();
                $row['user_sex']    =   M('users')->getFieldByUserId($row['user_id'],'sex');
                $row['headimgurl']  =   M('users')->getFieldByUserId($row['user_id'],'headimgurl');
                $row['con_count'] = mb_strlen($row['content'],'utf-8');
                $row['con_len'] = msubstr($row['content'],0,99);
            }
        }
        $this->assign('datas',$data);
        $this->display();
    }
    /*
     * 删除帖子
     * */
    public function del_message(){
        if(IS_POST){
            $msg_id = I('post.msg_id');
            $res = M('Message')->where(array('message_id'=>$msg_id,'user_id'=>$this->u_id))->setField('status',0);
            $res !== false ?$this->ajaxReturn(array('msg'=>'删除成功','status'=>1)):$this->ajaxReturn(array('msg'=>'删除失败','status'=>0));
        }

    }
}